<!-- 标签管理页面 (独立页面 tag-management.html) -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>标签管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <style>
        .container { max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
        .tag-item { display: flex; align-items: center; justify-content: space-between; padding: 0.8rem; background: #f5f5f5; border-radius: 8px; margin-bottom: 0.5rem; }
        .tag-actions button { margin-left: 0.5rem; border: none; background: none; cursor: pointer; }
        .tag-form { margin: 2rem 0; padding: 1.5rem; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .input-field { width: 100%; padding: 0.8rem; margin-bottom: 1rem; border: 1px solid #ddd; border-radius: 4px; }
        .btn { padding: 0.6rem 1.2rem; border: none; border-radius: 4px; cursor: pointer; }
        .btn-primary { background: #3b82f6; color: white; }
        .btn-danger { background: #ef4444; color: white; }
    </style>
</head>
<body>
<div class="container">
    <h1>标签管理</h1>

    <!-- 新建标签表单 -->
    <div class="tag-form">
        <h2>创建新标签</h2>
        <input type="text" id="new-tag-name" class="input-field" placeholder="输入标签名称">
        <button id="create-tag" class="btn btn-primary">
            <i class="fa fa-plus"></i> 创建标签
        </button>
    </div>

    <!-- 标签列表 -->
    <div>
        <h2>我的标签</h2>
        <div id="tag-list"></div>
        <div id="empty-state" style="display: none; text-align: center; padding: 2rem; color: #666;">
            暂无标签，点击上方按钮创建
        </div>
    </div>
</div>

<script>
    // 状态管理
    const state = {
        apiBaseUrl: 'http://localhost:8080', // 与主页面保持一致的API地址
        currentUser: {
            token: localStorage.getItem('token'),
            username: localStorage.getItem('username'),
            userId: localStorage.getItem('userId'),
            isAdmin: localStorage.getItem('isAdmin') === 'true'
        }, // 使用正确的存储键名
        tags: []
    };
    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
        // 检查是否有有效的token
        if (!state.currentUser.token) {
            alert('请先登录');
            window.location.href = 'login.html';
            return;
        }
        loadTags();
        bindEvents();
    });

    // 加载所有标签
    async function loadTags() {
        try {
            const response = await fetch(`${state.apiBaseUrl}/tags/user`, {
                headers: {
                    'Authorization': `Bearer ${state.currentUser.token}`
                }
            });

            if (!response.ok) throw new Error('加载标签失败');

            state.tags = await response.json();
            renderTags();
        } catch (error) {
            alert(error.message);
        }
    }

    // 渲染标签列表
    function renderTags() {
        const tagList = document.getElementById('tag-list');
        const emptyState = document.getElementById('empty-state');

        if (state.tags.length === 0) {
            tagList.innerHTML = '';
            emptyState.style.display = 'block';
            return;
        }

        emptyState.style.display = 'none';
        tagList.innerHTML = state.tags.map(tag => `
                <div class="tag-item" data-id="${tag.id}">
                    <span>${tag.name}</span>
                    <div class="tag-actions">
                        <button class="edit-tag" data-id="${tag.id}" data-name="${tag.name}">
                            <i class="fa fa-pencil" style="color: #6b7280;"></i>
                        </button>
                        <button class="delete-tag" data-id="${tag.id}">
                            <i class="fa fa-trash" style="color: #ef4444;"></i>
                        </button>
                    </div>
                </div>
            `).join('');
    }

    // 绑定事件
    function bindEvents() {
        // 创建标签
        document.getElementById('create-tag').addEventListener('click', createTag);

        // 标签列表事件委托
        document.getElementById('tag-list').addEventListener('click', (e) => {
            const tagId = parseInt(e.target.closest('[data-id]')?.dataset.id);
            if (!tagId) return;

            if (e.target.closest('.edit-tag')) {
                editTag(tagId);
            } else if (e.target.closest('.delete-tag')) {
                deleteTag(tagId);
            }
        });

        // 回车创建标签
        document.getElementById('new-tag-name').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') createTag();
        });
    }

    // 创建标签
    async function createTag() {
        const tagName = document.getElementById('new-tag-name').value.trim();
        if (!tagName) {
            alert('请输入标签名称');
            return;
        }

        try {
            const response = await fetch(`${state.apiBaseUrl}/tags`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${state.currentUser.token}`
                },
                body: JSON.stringify({ name: tagName })
            });

            if (!response.ok) throw new Error('创建标签失败');

            document.getElementById('new-tag-name').value = '';
            await loadTags();
            alert('标签创建成功');
        } catch (error) {
            alert(error.message);
        }
    }

    // 编辑标签
    async function editTag(tagId) {
        const tag = state.tags.find(t => t.id === tagId);
        if (!tag) return;

        const newName = prompt('修改标签名称', tag.name);
        if (!newName || newName.trim() === tag.name) return;

        try {
            const response = await fetch(`${state.apiBaseUrl}/tags/${tagId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${state.currentUser.token}`
                },
                body: JSON.stringify({ name: newName.trim() })
            });

            if (!response.ok) throw new Error('更新标签失败');

            await loadTags();
            alert('标签更新成功');
        } catch (error) {
            alert(error.message);
        }
    }

    // 删除标签
    async function deleteTag(tagId) {
        if (!confirm('确定要删除这个标签吗？')) return;

        try {
            const response = await fetch(`${state.apiBaseUrl}/tags/${tagId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${state.currentUser.token}`
                }
            });

            if (!response.ok) throw new Error('删除标签失败');

            await loadTags();
            alert('标签已删除');
        } catch (error) {
            alert(error.message);
        }
    }
</script>
</body>
</html>